package com.qyhl.module_practice.substreet.fragment;

import android.os.Bundle;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeListBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

public class SubStreetFragment extends BaseFragment implements SubStreetContract.SubStreetView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;


    private String id;

    public void setInstId(String id) {
        this.id = id;
    }

    private SubStreetPresenter mPresenter;

    private CommonAdapter commonAdapter;

    private List<PracticeListBean> mDataList = new ArrayList<>();

    private String type;

    private int page = 1;

    public void setType(String type) {
        this.type = type;
    }

    private int volStatus;

    private String volId;

    public void setVolId(String volId) {
        this.volId = volId;
    }

    public void setVolStatus(int volStatus) {
        this.volStatus = volStatus;
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.practice_fragment_substreet, null);
    }

    @Override
    public void initImmersionBar() {

    }

    @Override
    protected void create() {
        mPresenter = new SubStreetPresenter(this);

        loadMask.setStatus(LoadingLayout.Loading);

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setEnableLoadMore(true);

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager);

        recycleView.setAdapter(commonAdapter = new CommonAdapter<PracticeListBean>(getContext(), R.layout.practice_item_street_list, mDataList) {
            @Override
            protected void convert(ViewHolder holder, PracticeListBean bean, int position) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(getContext().getApplicationContext())
                        .load(bean.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default))
                        .into(cover);

                holder.setText(R.id.title, bean.getName());

                holder.setText(R.id.score, "爱心积分：" + bean.getScore() + "分");

                holder.setText(R.id.act, "活动：" + bean.getActTotal() + "场");

                holder.setText(R.id.vol, "志愿者：" + bean.getVolTotal() + "人");

                holder.setText(R.id.adress, bean.getAddress());

                holder.setText(R.id.phone, bean.getTelephoneNum());

                if (type.equals("2")) {
                    holder.setVisible(R.id.score, false);
                } else {
                    holder.setVisible(R.id.score, true);
                }

                if (bean.getAct() != null && bean.getAct().getStatus() != null) {
                    holder.setVisible(R.id.activity, true);
                    holder.setVisible(R.id.divider_line, true);
                    TextView activity = holder.getView(R.id.activity);
                    SpanUtils spanUtils = new SpanUtils(getContext());
                    switch (bean.getAct().getStatus()) {
                        case "NOT_BEGIN":
                            spanUtils.append("未开始：").setSpans(new TextAppearanceSpan(getActivity(), R.style.practice_activity_txt_on));
                            break;
                        case "RECRUIT":
                            spanUtils.append("招募中：").setSpans(new TextAppearanceSpan(getActivity(), R.style.practice_activity_txt_on));
                            break;
                        case "SERVICE":
                            spanUtils.append("服务中：").setSpans(new TextAppearanceSpan(getActivity(), R.style.practice_activity_txt_on));
                            break;
                        case "BEGINNING":
                            spanUtils.append("进行中：").setSpans(new TextAppearanceSpan(getActivity(), R.style.practice_activity_txt_on));
                            break;
                        case "END":
                            spanUtils.append("已结束：").setSpans(new TextAppearanceSpan(getActivity(), R.style.practice_activity_txt_on));
                            break;
                        default:
                            break;
                    }
                    spanUtils.append(bean.getAct().getName()).setSpans(new TextAppearanceSpan(getContext(), R.style.practice_activity_txt_off));
                    activity.setText(spanUtils.create());
                } else {
                    holder.setVisible(R.id.activity, false);
                    holder.setVisible(R.id.divider_line, false);
                }

            }
        });

        mPresenter.getList(id, type, page + "");
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            page = 1;
            mPresenter.getList(id, type, page + "");
        });

        refresh.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getList(id, type, page + "");
        });

        refresh.setOnLoadMoreListener(refreshLayout -> mPresenter.getList(id, type, page + ""));

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                Bundle bundle = new Bundle();
                bundle.putString("instId", id);
                bundle.putString("streetId", mDataList.get(position).getId() + "");
                bundle.putString("title", mDataList.get(position).getName());
                bundle.putInt("status", volStatus);
                bundle.putString("volId", volId);

                RouterManager.router(ARouterPathConstant.PRACTICE_STREET_DETAIL, bundle);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    public static SubStreetFragment newInstance(String volId, int volStatus, String id, String type) {
        SubStreetFragment fragment = new SubStreetFragment();
        fragment.setInstId(id);
        fragment.setType(type);
        fragment.setVolStatus(volStatus);
        fragment.setVolId(volId);
        return fragment;
    }

    @Override
    public void setList(List<PracticeListBean> beanList, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            loadMask.setStatus(LoadingLayout.Success);
            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(Objects.requireNonNull(getContext()))) {
                showToast("网络异常，请检查您的网络！", 4);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(Objects.requireNonNull(getContext()))) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }
}
